import { Category } from "@/models/Category";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";

const categoryRoute = new Hono();

categoryRoute.get("/list", async (c) => {
  let [list, count] = await Category.findAndCount();
  return c.json({ message: "success", code: 200, data: { list, count } });
});

const addSchema = z.object({
  name: z.string(),
  image: z.string().optional(),
});

const updateSchema = z.object({
  id: z.coerce.number(),
  name: z.string(),
  image: z.string().optional(),
});

categoryRoute.post("/add", async (c) => {
  let body = await c.req.parseBody();
  let result = addSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let category = new Category();
  category.name = result.data.name;
  category.image = result.data.image;
  await category.save();

  return c.json({ message: "hello", code: 200, data: category });
});

categoryRoute.post("/edit", async (c) => {
  let body = await c.req.parseBody();
  let result = updateSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let category = await Category.findOneBy({ id: result.data.id });

  if (!category) {
    throw new HTTPException(404, { message: "分类不存在" });
  }

  category.name = result.data.name;
  category.image = result.data.image;
  await category.save();

  return c.json({ message: "hello", code: 200, data: category });
});

export default categoryRoute;
